package com.hm.health.Utils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by jiaguang on 2019/6/27.
 */

public class TimerUtil {

    private Timer mTimer;
    private TimerTask mTimerTask;
    private int mTimeInterval;

    public TimerUtil(int timeInterval, TimerTaskToRun TimerTaskToRun){
        mTimeInterval = timeInterval;
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                if (mIsRunning && null != TimerTaskToRun) {
                    TimerTaskToRun.run();
                }
            }
        };
    }

    private volatile boolean mIsRunning = false;

    public void startTimer() {
        mIsRunning = true;
        mTimer.schedule(mTimerTask, 0, mTimeInterval);
    }

    public void cancel(){
        mIsRunning = false;
        if (null != mTimer) {
            mTimer.cancel();
        }
    }

    public void pause(){
        mIsRunning = false;
    }

    public void resume(){
        mIsRunning = true;
    }

    public interface TimerTaskToRun {
        void run();
    }
}
